package com.library.aspect;

import com.library.security.TokenProvider;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.server.ResponseStatusException;
import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class TokenValidationAspect {

    private final TokenProvider tokenProvider;

    public TokenValidationAspect(TokenProvider tokenProvider) {
        this.tokenProvider = tokenProvider;
    }

    @Pointcut("within(@org.springframework.web.bind.annotation.RestController *) && " +
            "execution(* com.library.controller..*(..)) && " +
            "!execution(* com.library.controller.AuthController.login(..))")
    public void securedEndpoints() {}

    @Before("securedEndpoints()")
    public void validateToken() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "No request attributes available");
        }

        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader("Authorization");

        if (token == null || token.isEmpty()) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Token is missing");
        }

        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        if (!tokenProvider.validateToken(token)) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid or expired token");
        }
    }
}
